package no.ntnu.fp.client;

import java.io.DataOutputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.LinkedList;
import java.util.List;

import no.ntnu.fp.model.Appointment;
import no.ntnu.fp.model.Person;
import no.ntnu.fp.model.SuperPackage;
import no.ntnu.fp.net.co.MessageListener;
import no.ntnu.fp.net.co.MessageReceiver;
import no.ntnu.fp.server.Server;
import nu.xom.ParsingException;
import nu.xom.ValidityException;

public class ClientConnectionHandler implements MessageListener {
	
	private Socket socket;
	private DataOutputStream out;
	private StringBuilder messageBuilder;
	private ClientModelHandler mh;
	
	public ClientConnectionHandler(int port) {
		
		try {
			socket = new Socket(InetAddress.getLocalHost(), port);
			out = new DataOutputStream(socket.getOutputStream());
		} 
		catch (UnknownHostException e) {} 
		catch (IOException e) {}
		
		mh = new ClientModelHandler(this);
		messageBuilder = new StringBuilder(/*1024*/);
		new Thread(new MessageReceiver(socket, this)).start();
	}

	public void send(String data) {
		System.out.println("Sending to server");
		try {
			out.writeBytes(data+"\n");
		} catch (IOException e) {
			System.err.println("Failed to send to server");
		}
	}

	public synchronized void messageReceived(String message) {
		System.err.println("CLIENT: " + message);
		messageBuilder.append(message);

		if (message.endsWith("</superpakke>")) {
			//mh.updateModels(message);
			messageBuilder = new StringBuilder(/*1024*/);
		}
	}
	
	public static void main(String[] args) throws InterruptedException {
		
		new Server();
		
		ClientConnectionHandler c = new ClientConnectionHandler(1502);
		
		Thread.sleep(1000);
		
		System.out.println(Person.get(1).name);
	}
}
